package com.example.administrator.baikangxing;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.example.administrator.baikangxing.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;


public class MyApplication extends MultiDexApplication {
    private final static String PROCESS_NAME = "com.example.administrator.baikangxing";
    public static Context context;
    public static List<Object> activitys = new ArrayList<Object>();
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        if (isAppMainProcess()) {
            context = this;
            JPushInterface.setDebugMode(true);
            JPushInterface.init(this);
            LogUtil.e("Myapplication初始化了！！！！");
        }

    }

    //获取单例模式中唯一的MyApplication实例
    public static MyApplication getInstance() {
        return instance;
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        if (!activitys.contains(activity))
            activitys.add(activity);
    }

    // 遍历所有Activity并finish
    public void destory() {
        for (Object activity : activitys) {
            if (activity != null) {
                ((Activity) activity).finish();
            }
        }
    }

    @Nullable
    public static String getProcessName(Context context, int pid){
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps != null && !runningApps.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
        }
        return null;
    }

    public static boolean isAppMainProcess() {
        try {
            int pid = android.os.Process.myPid();
            LogUtil.e("进程："+pid+"");
            String process = getProcessName(MyApplication.getInstance(), pid);
            if (TextUtils.isEmpty(process)) {
                return true;
            } else if (PROCESS_NAME.equalsIgnoreCase(process)) {
                LogUtil.e("进程名称："+process);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }
}
